<template>
  <div class="goods-list-container">
    <MyHeader></MyHeader>
    <MyTable :list="list">
      <template #header>
        <th></th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <!-- {{ scope.row.tags }} -->
      <template #body="scope">
        <td>{{ scope.row.id }}</td>
        <td>{{ scope.row.goods_name }}</td>
        <td>{{ scope.row.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            v-if="scope.row.inputVisible"
            type="text"
            v-focus
            @blur="scope.row.inputVisible = false"
            @keydown.enter="enter(scope.row)"
            v-model="scope.row.inputValue"
          />
          <button
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            v-else
            @click="scope.row.inputVisible = true"
          >
            +tag
          </button>
          <span
            v-for="(item, index) in scope.row.tags"
            :key="index"
            class="badge bg-warning text-dark"
          >
            {{ item }}
          </span>
        </td>
        <td>
          <button class="btn btn-sm btn-danger" @click="del(scope.row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyHeader from "../components/MyHeader.vue";
import MyTable from "../components/MyTable";
import axios from "axios";
axios.defaults.baseURL = "https://www.escook.cn";
// 目标: 循环商品列表表格
// 1. 封装MyTable.vue 整体表格组件-一套标签和样式
// 2. axios请求数据
// 3. 传入MyTable组件里循环tr显示数据

// 目标: 展示tags标签
// 1. tags数组 - 某个td循环span使用文字
// 2. span设置bs的样式

// 目标: 删除数据
// 1. 删除按钮 - 点击事件
// 2. 作用域插槽把索引值关联出来了
// scope身上就有row和index
// 3. 删除中使用scope.index的索引值
// 4. 删除事件里删除数组里对应索引值的数据
export default {
  components: {
    MyTable,
    MyHeader,
  },
  data() {
    return {
      list: [], // 所有数据
    };
  },
  methods: {
    /* 删除 */
    del(id) {
      let index = this.list.findIndex((item) => (item.id = id));
      this.list.splice(index, 1);
    },
    enter(obj) {
      if (obj.inputValue.trim().length === 0) {
        alert("请输入数据");
        return;
      }
      obj.tags.push(obj.inputValue.trim());
      obj.inputValue = "";
    },
  },
  async created() {
    let res = await axios({
      url: "/api/goods",
    });

    this.list = res.data.data;
    /* console.log(this.list); */
  },
};
</script>

<style lang="less" scoped>
.goods-list-container {
  padding-top: 45px;
  .badge {
    margin-right: 5px;
  }
}
</style>